#!/usr/bin/env python

# Manger.py
#
# Contains the manager class to instanciate pygame
# and start the main loop

import sys
sys.path.append('depends')

import pygame
from pygame.locals import *
import crowd, conversation, tweet, background, button
import conversationSurface, replySurface, eztext
import random
import simplejson
import twitter
import getpass

api = None
timer = 30
profile_image = None
username = None

def updateCrowd():
	global api
	currentCrowd = crowd.Crowd()
	print "Checking for updates"
	updates = api.Get362Timeline()

	found = False
	for update in updates:
		inConvo = False
		replyingTo = False
		
		for currentConversation in currentCrowd.conversations:
			for convoTweet in currentConversation.tweetList:
				if str(convoTweet.id) == str(update.id):
					inConvo = True
				if str(convoTweet.id) == str(update.in_reply_to_status_id):
					replyingTo = True
		
			if not inConvo and replyingTo:
				newTweet = tweet.Tweet(update.text, update.id, update.user.screen_name, update.user.profile_image_url)
				currentConversation.addTweet(newTweet)
				print "Added " + str(newTweet.id) + " to " + str(convoTweet.id)
				break
		
		if not inConvo and not replyingTo:
			conversation.Conversation(tweet.Tweet(update.text, update.id, update.user.screen_name, update.user.profile_image_url))
			print "Created " + str(update.id)

	print "Done"

def drawLoginScreen(screen, backGroup):
	global api
	global profile_image
	gotUser = False
	user = ""
	gotPass = False
	passW = ""
	logScreen = pygame.Surface((1024,768))
	logScreen.fill((0,0,0))
	logScreen.set_alpha(175)
	shadowSur = pygame.Surface((700, 100))
	shadowSur.fill((16,78,139))
	shadowRect = shadowSur.get_rect()
	shadowRect.center = (505, 390)
	solidSurf = pygame.Surface((700, 100))
	solidSurf.fill((30,144,255))
	solidRect = solidSurf.get_rect()
	solidRect.center = (512, 384)
	# create the textbox
	txtbx = eztext.Input(maxlength=50, color=(0,0,0), prompt='Username: ')
	txtbx.set_pos(162, 370)
	while not gotUser:
		events = pygame.event.get()
		for event in events:
			if event.type == QUIT:
				gotUser = True
			elif event.type == KEYDOWN and event.key == K_ESCAPE:
				gotUser = True
			elif event.type == KEYDOWN and event.key == K_RETURN:
				user = txtbx.value
				gotUser = True
		
		txtbx.update(events)

		backGroup.draw(screen)
		screen.blit(logScreen, (0,0))
		screen.blit(shadowSur, shadowRect.topleft)
		screen.blit(solidSurf, solidRect.topleft)
		txtbx.draw(screen)
		pygame.display.flip()

	txtbx = eztext.Input(maxlength=50, color=(0,0,0), prompt='Password: ')
	txtbx.set_pos(162, 370)
	while not gotPass:
		events = pygame.event.get()
		for event in events:
			if event.type == QUIT:
				gotPass = True
			elif event.type == KEYDOWN and event.key == K_ESCAPE:
				gotPass = True
			elif event.type == KEYDOWN and event.key == K_RETURN:
				passW = txtbx.value
				gotPass = True
		
		txtbx.update(events)

		backGroup.draw(screen)
		screen.blit(logScreen, (0,0))
		screen.blit(shadowSur, shadowRect.topleft)
		screen.blit(solidSurf, solidRect.topleft)
		txtbx.draw(screen)
		pygame.display.flip()

	# Instanciate API
	api = twitter.Api(user,passW)
	myUser = api.GetUser(user)
	profile_image = myUser.GetProfileImageUrl()
	username = myUser.GetScreenName()

class Manager(object):
	_instance = None
	def __init__(self):
		"""this function is called when the program starts.
		 it initializes everything the game needs.  """
		# Initilize Crowd
		crowd.gatherCrowd()
		pygame.init()
		pygame.key.set_repeat()
		self.ticks = pygame.time.get_ticks()
		self.screen = pygame.display.set_mode((1024, 768))
		pygame.display.set_caption('Twitter 362')
		pygame.mouse.set_visible(True)
		self.backGroup = pygame.sprite.Group()
		self.backGroup.add(background.Background())
		self.myCrowd = crowd.Crowd()
		self.upButton = button.Button("uparrow.gif", 930, 675)
		self.downButton = button.Button("downarrow.gif", 930, 715)
		self.backButton = button.Button("back.gif", 1, 710)
		self.replyButton = button.Button("reply.gif", 1, 655)
		self.buttonGroup = pygame.sprite.Group()
		self.buttonGroup.add(self.upButton)
		self.buttonGroup.add(self.downButton)
		self.buttonGroup.add(self.backButton)
		self.buttonGroup.add(self.replyButton)


	def play(self):
		global api
		global timer
		global profile_image
		global username
		sinceUpdate = 0
		done = False
		self.ticks = pygame.time.get_ticks();
		replyScreen = None
		conScreen = None
		selectedCon = None
		drawMain = True
		drawReply = False
		lastUpdate = 0
		self.backGroup.draw(self.screen)
		pygame.display.flip()
		drawLoginScreen(self.screen, self.backGroup)
		self.backGroup.draw(self.screen)
		pygame.display.flip()
		updateCrowd()
		while not done:
			if drawMain:
				for event in pygame.event.get():
					if event.type == QUIT:
						done = True
					elif event.type == KEYDOWN and event.key == K_ESCAPE:
						done = True
					elif event.type == MOUSEBUTTONDOWN and event.button == 1:
						# Check if a conversation anchor was clicked
						clickedCon = self.myCrowd.checkClicked(event.pos)
						if clickedCon:
							conScreen = clickedCon.getConverSurface()
							drawMain = False

				# Update the Background
				self.backGroup.update()
				# Update the Conversations
				self.myCrowd.update()

				# Draw the main window
				self.backGroup.draw(self.screen)
				self.myCrowd.draw()

			else:
				events = pygame.event.get()
				for event in events:
					if event.type == QUIT:
						done = True
					elif event.type == KEYDOWN and event.key == K_ESCAPE:
						done = True
					elif event.type == KEYDOWN and event.key == K_RETURN and drawReply:
						# User pressed enter on the reply screen
						# Send the value in the txtbx as a tweet
						# and add it to the current conversation
						id = conScreen.displayCon.tweetList[0].id
						
						newReply = api.PostUpdate(txtbx.value,id)
						newTweet = tweet.Tweet(txtbx.value,newReply.id,username,profile_image)
						conScreen.displayCon.addTweet(newTweet)
						# Quit drawing the reply screen
						drawReply = False
						
					elif event.type == MOUSEBUTTONDOWN and event.button == 1:
						# Check if button was clicked
						for menuButton in self.buttonGroup:
							clickedButton = menuButton.checkClick(event.pos)
							if clickedButton != None:
								break
						if clickedButton != None:
							if clickedButton == self.upButton and not drawReply:
								conScreen.moveUp()
							elif clickedButton == self.downButton and not drawReply:
								conScreen.moveDown()
							elif clickedButton == self.backButton and not drawReply:
								# back button is hit go back to the main screen
								drawMain = True
							elif clickedButton == self.replyButton:
								# Reply button clicked. Draw reply screen
								drawReply = True
								# Get surface to draw
								replyScreen = replySurface.ReplySurface(conScreen.displayCon)
								# create the textbox
								txtbx = eztext.Input(maxlength=50, color=(0,0,0), prompt='Reply: ')
								txtbx.value = "@" + conScreen.displayCon.tweetList[0].username + " "
								txtbx.set_pos(162, 370)
								
					elif event.type == MOUSEBUTTONUP and event.button == 1:
						# Let off click stop screen from scrolling
						conScreen.stop()
				
				
				# Update conversation screen
				conScreen.update()
				# Draw a conversation
				conScreen.draw(self.screen)

				# Draw Buttons
				self.buttonGroup.draw(self.screen)
				
				# Draw Reply screen if there is one to draw
				if drawReply:
					# Update the text box
					txtbx.update(events)
					# Draw the reply Screen
					replyScreen.draw(self.screen)
					# blit txtbx on the sceen
					txtbx.draw(self.screen)
					
		
			if (pygame.time.get_ticks() - lastUpdate) > (timer * 1000):
				updateCrowd()
				lastUpdate = pygame.time.get_ticks()
			pygame.display.flip()


if __name__ == "__main__":
	#user = raw_input('Username: ')
	#password = getpass.getpass()
	#api = twitter.Api(user,password)
	
	man = Manager()
	man.play()

